#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
@File    :   cmdb_api.py
@Time    :   2023-08-31 16:02:54
@Author  :   Li Rui
@Version :   1.0
@Contact :   marjey_lee@163.com
@Desc    :   None
"""
import json

import requests

from ll import read_all_sheet_xls_mapping


class CMDBAPI:
    def __init__(self) -> None:
        self.base_url = "http://blk-paas.fdb.com/api/c/compapi/v2/cc/"
        self.select_prefix = "search_inst/"
        self.insert_prefix = "create_inst/"
        self.update_prefix = "update_inst/"
        self.delete_prefix = "delete_inst/"
        self.secret = "fd11245d-074f-4d89-ae40-a170a2faf82c"
        self.app_code = "bk_sops"
        self.username = "01639"

    def insert_instance(self, obj_id, instance_data):
        """

        Args:
            obj_id:
            instance_data:

        Returns:

        """
        url = self.base_url + self.insert_prefix
        template = {
            "bk_app_code": self.app_code,
            "bk_app_secret": self.secret,
            "bk_username": self.username,
            "bk_obj_id": obj_id,
            **instance_data,
        }
        result = requests.post(url, json=template).text
        result = json.loads(result)
        return result

    def select_all(self, obj_id):
        """_summary_

        Args:
            obj_id :table id
        """
        url = self.base_url + self.select_prefix
        return self._post_info(url, obj_id)

    def _post_info(
            self,
            url,
            obj_id,
    ):
        """post request

        Args:
            url (_type_): _description_
        """
        template = {
            "bk_app_code": self.app_code,
            "bk_app_secret": self.secret,
            "bk_username": self.username,
            "bk_obj_id": obj_id,
        }
        result = requests.post(url, json=template).text
        result = json.loads(result)
        return result


def insert_demo():
    api = CMDBAPI()
    # res = api.select_all('network_device_asset')
    content = read_all_sheet_xls_mapping(r'C:\Users\fdb\Desktop\1.xls')['network_device_asset']
    for item in content:
        item['room_number'] = str(int(item['room_number']))
        item['floor'] = str(int(item['floor']))
        if isinstance(item['bk_inst_name'], float):
            item['bk_inst_name'] = str(int(item['bk_inst_name']))
        if isinstance(item['serial_number'], float):
            item['serial_number'] = str(int(item['serial_number']))
        res = api.insert_instance('network_device_asset', item)
        if res['code'] not in [0, 1199014]:
            print(res)


def _main():
    pass


if __name__ == "__main__":
    _main()
